package com.example.ResponsibleChainPattern_LinkedList;

import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.List;

/**
 * <pre>
 * 功能描述：
 * </pre>
 *
 * @author: 李明杰
 * @date: 2022/10/27 22:21
 */
@Component
public class FilterExecutionChain {

    //自动注入各个责任链的对象【@Order注解已经排序过了】
    @Resource
    private List<AbstractHandler> abstractHandleList;

    private AbstractHandler abstractHandler;

    //spring注入后自动执行，责任链的对象连接起来
    @PostConstruct
    public void initializeChainFilter() {

        for (int i = 0; i < abstractHandleList.size(); i++) {
            if (i == 0) {
                abstractHandler = abstractHandleList.get(0);
            } else {
                AbstractHandler currentHandler = abstractHandleList.get(i - 1);
                AbstractHandler nextHandler = abstractHandleList.get(i);
                currentHandler.setNextHandler(nextHandler);
            }
        }

    }

    //直接调用这个方法使用
    public void exec(String request, String response) {
        abstractHandler.filter(request, response);
    }

    public AbstractHandler getAbstractHandler() {
        return abstractHandler;
    }

    public void setAbstractHandler(AbstractHandler abstractHandler) {
        this.abstractHandler = abstractHandler;
    }
}

